package com.common.aop;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.common.user.domain.User;
import com.common.user.service.UserService;

@Aspect
@Component
@Order(-5)
public class WebLogAspect {
	
	@Autowired
	private UserService userService;

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Pointcut("execution(* com.common.*.controller..*.*(..))")
	public void webLog() {}
	
	@Before("webLog()")
	public void doBefore(JoinPoint joinPoint) {
		
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String method =  joinPoint.getSignature().getName();
        String[] className = joinPoint.getSignature().getDeclaringTypeName().split("\\.");
        String objectName = className[className.length - 1].replaceAll("Controller", "");
        
		logger.info(
					request.getRemoteAddr() + " "	
					+ "[" + getCurrentUsername(request) + "]" + " "
					+ method + " "
					+ objectName + " "
					+ Arrays.toString(joinPoint.getArgs()) );
	}
	
	String getCurrentUsername(HttpServletRequest request) {
	
		User currentUser =  userService.getCurrentUser(request);
		if(currentUser == null) {
			return "匿名用户";
		}
		
		return currentUser.getUsername();
	}
}
